<script setup lang="ts">
import { userApi } from "@/api/admin/user";
import { deepClone } from "@/utils";
import { ElDialog, ElForm, ElInput, ElFormItem, ElMessage, ElButton, ElSelectV2 } from "element-plus";
import { nextTick, ref } from "vue";
import { imgUpload } from "@/components/MyUpload";
const isEditor = ref(false);
const visible = ref(false);

class UserForm {
  avatar = "";
  id = null;
  account = "";
  password = "";
  roles: any = [];
}

const imgUploadRef = ref<any>(null);

const userForm = ref(new UserForm());

const userFormRef = ref();

// const { roleData } = defineProps({
//   roleData: {
//     type: Object,
//     default: {},
//   },
// });

const emit = defineEmits(["update"]);

const { roleOptions } = defineProps({
  roleOptions: {
    type: Array,
    default: [],
  },
});

const batchUser = ref<any>([]);

const isBatch = ref(false);

// 打开弹窗
const open = (data: any = null, Batch: boolean = false) => {
  visible.value = true;

  if (Batch) {
    isBatch.value = Batch;
    isEditor.value = true;
    batchUser.value = data;
    userForm.value = { ...data[0], roles: data[0].roles.map((item: any) => item.id) };
    return;
  }

  if (data) {
    isEditor.value = true;
    userForm.value = data;
    if (data.avatar) {
      // file[0].response?.data.url
      nextTick(() => {
        imgUploadRef.value.setFile([{ response: { data: { url: data.avatar } }, uid: '1' }]);
      })
    }
  } else {
    isEditor.value = false;
    userForm.value = new UserForm();
  }
};

// 取消
const handleCancel = () => {
  // clearForm();
  imgUploadRef.value.setFile([]);
  visible.value = false;
};

// 关闭弹窗
const handleClose = (deno: () => void) => {
  // clearForm();
  handleCancel()
  deno();
};

const handleUploadSuccess = (response: any,) => {
  // console.log(response, uploadFile);
  userForm.value.avatar = response.data.url;
};

const handleOk = async () => {
  let ret = null;

  await userFormRef.value.validate();

  const newUserForm = deepClone(userForm.value);

  newUserForm.roles = userForm.value.roles.map((item: any) => {
    return {
      id: item,
    }
  });
  if (!isEditor.value) {
    ret = await userApi.saveUser(newUserForm);
  } else {
    ret = await userApi.updateUser(newUserForm);
  }

  if (ret.code === 200) {
    ElMessage.success("操作成功");
    emit("update");
    visible.value = false;
    return true;
  } else {
    ElMessage.error(ret.data.msg);
    return false;
  }
};

// 提交并修改下一个
const handleOkAndNext = async () => {
  const isOk = await handleOk();
  if (isOk) {
    batchUser.value.shift();
    if (batchUser.value.length !== 0) {
      visible.value = true;
      userForm.value = { ...batchUser.value[0], roles: batchUser.value[0].roles.map((item: any) => item.id) };
      // console.log(batchUser.value);
    } else {
      isBatch.value = false;
      isEditor.value = false;
      return
    }
  }
};


// 暴露方法
defineExpose({
  open,
});
</script>

<template>
  <el-dialog :title="isEditor ? '修改' : '新增'" :before-close="handleClose" v-model="visible">
    <el-form ref="userFormRef" :model="userForm">
      <el-form-item prop="avatar" label="头像" :rules="[{ required: true, message: '请上传头像' }]">
        <imgUpload ref="imgUploadRef" @handleUploadSuccess="handleUploadSuccess" :is-avatar="true"
          uploadUrl="/common/upload" />
      </el-form-item>
      <el-form-item prop="account" label="账号" :rules="[{ required: true, message: '请输入用户名' }]">
        <el-input placeholder="请输入账号" v-model="userForm.account" />
      </el-form-item>
      <el-form-item v-if="!isEditor" prop="password" label="密码" :rules="[{ required: true, message: '请输入密码' }]">
        <el-input placeholder="请输入密码" v-model="userForm.password" />
      </el-form-item>
      <el-form-item v-else prop="password" label="新密码">
        <el-input placeholder="请输入密码,为空时不会修改原密码" v-model="userForm.password" />
      </el-form-item>
      <el-form-item prop="roles" label="角色" :rules="[{ required: true, message: '请选择角色' }]">
        <el-select-v2 v-model="userForm.roles" :options="roleOptions as any" placeholder="请选择角色" multiple />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleOk">
          {{ isEditor ? "提交修改" : "添加" }}
        </el-button>
        <el-button v-if="isBatch" type="primary" @click="handleOkAndNext">
          提交并修改下一个
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style lang="less" scoped></style>
